package Middleware

import (
	"net/http"

	"github.com/gin-gonic/gin"

	"hyper/supports/auth"
	"hyper/supports/jwt"
	"hyper/supports/response"
)

func AuthMiddleware() gin.HandlerFunc {

	return func(c *gin.Context) {

		// 从标头 Authorization:Bearer xxxxx 中获取信息，并验证 JWT 的准确性
		claims, err := jwt.GetTokenFromHeader(c)

		id, _ := auth.Auth("id", c)
		// fmt.Println(claims)
		if err != nil {
			response.ResponseException(c, http.StatusUnauthorized, err.Error(), "")
			c.Abort()
			return
		}

		// token验证是否有效  ||   判断token是否在黑名单中
		if jwt.HashTokenInBlacklist(claims) || !jwt.VerifyToken(claims) {
			response.ResponseException(c, http.StatusUnauthorized, "登录过期，请重新登录！", nil)
			c.Abort()
			return
		}

		// JWT 解析成功，设置用户信息
		params, e := jwt.ParseToken(claims)
		if e != nil {
			response.ResponseException(c, http.StatusUnauthorized, "token解析错误！", nil)
			c.Abort()
			return
		}

		if id == 0 || id == "" {
			response.ResponseException(c, http.StatusUnauthorized, "token验证失败！", nil)
			c.Abort()
			return
		}

		// 将用户信息存入 gin.context 里，后续 auth 包将从这里拿到当前用户数据
		c.Set("admin_id", id)
		c.Set("admin_user_info", params)
		c.Next()
	}
}
